package com.example.controller.pc;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.annotation.Log;
import com.example.common.result.Result;
import com.example.entity.dto.pc.AddProductLineDeviceDto;
import com.example.entity.dto.pc.AddProductLineDto;
import com.example.entity.dto.pc.EditProductLineDto;
import com.example.entity.mysql.*;
import com.example.entity.vo.pc.ProductLineListVo;
import com.example.entity.yifei.Cmsmd;
import com.example.mapper.pc.ResourceMapper;
import com.example.mapper.pc.ResourcesubMapper;
import com.example.service.CmsmdService;
import com.example.service.pc.*;
import com.example.untils.BeanUtils;
import com.example.untils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "生产线资源管理")
@RequestMapping("/api/productLine")
public class ProductLineController {

    @Autowired
    private ResourcegroupService resourceGroupService;

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourcesubService resourcesubService;

    @Autowired
    private ResourcesubMapper resourcesubMapper;

    @Autowired
    private ProductprocessresourceService productprocessresourceService;

    @Autowired
    private WorkresourceService workresourceService;

    @Autowired
    private CmsmdService cmsmdService;

    @ApiOperation("末级生产线列表")
    @PostMapping("productLineList")
    public Result<List<ProductLineListVo>> productLineList() {

        List<Cmsmd> cmsmdList = cmsmdService.list();
        Map<String, String> cmsmdMap = new HashMap<>();
        for(Cmsmd cmsmd : cmsmdList) {
            cmsmdMap.put(cmsmd.getMd001().trim(), cmsmd.getMd002().trim());
        }

        List<ProductLineListVo> lineList = resourceMapper.productLineList();
        List<Integer> resourceGroupIdList = new ArrayList<>();
        for(ProductLineListVo vo : lineList) {
            vo.setWorkCenterName(cmsmdMap.get(vo.getWorkCenter().trim()));
            resourceGroupIdList.add(vo.getResourceGroupIdIsF());
        }
        List<Resourcesub> resourcesubs = resourcesubMapper.listVo(resourceGroupIdList);
        Map<Integer, List<Resourcesub>> map = new HashMap<>();
        for(Resourcesub resourcesub : resourcesubs) {
            List<Resourcesub> list = map.get(resourcesub.getResourceGroupId());
            if(list == null) list = new ArrayList<>();
            list.add(resourcesub);
            map.put(resourcesub.getResourceGroupId(), list);
        }
        for(ProductLineListVo vo : lineList) {
            vo.setSonList(map.get(vo.getResourceGroupIdIsF()));
        }
        return Result.success(lineList);
    }

    @ApiOperation("统驭生产线组列表")
    @PostMapping("productLineGroupList")
    public Result<List<ProductLineListVo>> productLineGroupList() {
        List<ProductLineListVo> lineList = resourceMapper.productLineGroupList();
        List<Integer> resourceGroupIdList = new ArrayList<>();
        for(ProductLineListVo vo : lineList) {
            resourceGroupIdList.add(vo.getResourceGroupIdIsF());
        }
        List<Resourcesub> resourcesubs = resourcesubMapper.listVo(resourceGroupIdList);
        Map<Integer, List<Resourcesub>> map = new HashMap<>();
        for(Resourcesub resourcesub : resourcesubs) {
            List<Resourcesub> list = map.get(resourcesub.getResourceGroupId());
            if(list == null) list = new ArrayList<>();
            list.add(resourcesub);
            map.put(resourcesub.getResourceGroupId(), list);
        }
        for(ProductLineListVo vo : lineList) {
            vo.setSonList(map.get(vo.getResourceGroupIdIsF()));
        }
        return Result.success(lineList);
    }


//    @ApiOperation("可编辑的生产线组（统驭下面至少有一个末级的）")
//    @PostMapping("productLineGroupList")
//    public Result<List<Resourcegroup>> productLineGroupList() {
//        List<Resourcegroup> list = resourceGroupService.list();
//        Map<Integer, List<Resourcegroup>> map = new HashMap<>();
//        Map<Integer, Resourcegroup> posMap = new HashMap<>();
//        for(Resourcegroup group : list) {
//            posMap.put(group.getResourceGroupId(), group);
//            List<Resourcegroup> resourcegroupList =
//                    map.get(group.getResourceGroupParentId() == null ? 0 : group.getResourceGroupParentId());
//            if(resourcegroupList == null) {
//                resourcegroupList = new ArrayList<>();
//            }
//            resourcegroupList.add(group);
//            map.put(group.getResourceGroupParentId() == null ? 0 : group.getResourceGroupParentId(), resourcegroupList);
//        }
//        return Result.success(getResList(map, posMap, 2));
//    }

    /**
     * 查询某个id节点子树中，节点直接下级中有末级的节点
     * @param map
     * @param posMap
     * @param id
     * @return
     */
    public List<Resourcegroup> getResList(Map<Integer, List<Resourcegroup>> map, Map<Integer, Resourcegroup> posMap,
                                          Integer id) {
        List<Resourcegroup> res = new ArrayList<>();
        List<Resourcegroup> list = map.get(id);
        if(list == null) return res;
        boolean flag = false;
        for(Resourcegroup t : list) {
            if("F".equals(t.getType())) {
                flag = true;
            }
            List<Resourcegroup> resList = getResList(map, posMap, t.getResourceGroupId());
            if(resList != null) {
                for(Resourcegroup resourcegroup : resList) {
                    res.add(posMap.get(resourcegroup.getResourceGroupId()));
                }
            }
        }
        if(flag) res.add(posMap.get(id));
        return res;
    }

    @Log("添加生产线末级")
    @ApiOperation("添加生产线末级")
    @PostMapping("addProductLine")
    @DSTransactional
    public Result addProductLine(@RequestBody AddProductLineDto dto) {
        if(StringUtils.isEmpty(dto.getDeviceid()) || StringUtils.isEmpty(dto.getDevicename())) {
            return Result.error("资源编号或资源名称不能为空");
        }
        if(dto.getResourceGroupId() == null) {
            return Result.error("资源组ID不能为空");
        }
//        Integer count = resourcegroupMapper.selectCount(new LambdaQueryWrapper<Resourcegroup>()
//                .eq(Resourcegroup::getResourceGroupId, resource.getResourceGroupId()));
//        if(count == null || count == 0) {
//            return Result.error("资源组ID不存在");
//        }
        Integer count = resourceService.count(new LambdaQueryWrapper<Resource>()
                .eq(Resource::getDeviceid, dto.getDeviceid()));
        if(count != null && count > 0) {
            return Result.error("资源编号已被使用");
        }
        // 添加Resourcegroup数据
        Resourcegroup resourcegroup = new Resourcegroup();
        resourcegroup.setType("F");
        resourcegroup.setResourceGroupNO(dto.getDeviceid());
        resourcegroup.setResourceGroupName(dto.getDevicename());
        resourcegroup.setResourceGroupParentId(dto.getResourceGroupId());
        resourceGroupService.save(resourcegroup);
//        // 添加resource数据
        Resource resource = new Resource();
        BeanUtils.copyPropertiesIgnoreCase(dto, resource);
        resource.setResourceType(2);
        resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
        boolean b = resourceService.save(resource);
        if(b) return Result.success("添加资源成功");
        else return Result.success("添加资源失败");
    }

    @ApiOperation("删除生产线末级")
    @PostMapping("delProductLine")
    @DSTransactional
    public Result delProductLine(@RequestBody Integer id) {
        Resource origin = resourceService.getById(id);
        // TODO 什么时候不能删？？
        // 如果是删除资源组，判断资源组不能被使用过。（品号工序资源管理， 生产排产）
        int count = productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>()
                .eq(Productprocessresource::getResourceGroupId, origin.getResourceGroupIdIsF()));
        if(count > 0) {
            return Result.error("品号工序资源管理中，数据已被使用。");
        }
        count = workresourceService.count(new LambdaQueryWrapper<Workresource>().eq(Workresource::getResourceGroupId, origin.getResourceGroupIdIsF()));
        if(count > 0) {
            return Result.error("[排产]--[生产线/设备]管理中，数据已被使用。");
        }
        resourceService.removeById(id);
        resourceGroupService.removeById(origin.getResourceGroupIdIsF());
        // 删除资源子表的值
        resourcesubMapper.delete(new LambdaQueryWrapper<Resourcesub>().eq(Resourcesub::getResourceGroupId, origin.getResourceGroupIdIsF()));
        return Result.success("删除成功");
    }

    @ApiOperation("编辑生产线末级")
    @PostMapping("editProductLine")
    @DSTransactional
    public Result editProductLine(@RequestBody EditProductLineDto dto) {

        Resource originItem = resourceService.getById(dto.getResourceId());
        if(originItem.getFixedLine() != null && !originItem.getFixedLine().equals(dto.getFixedLine())) {
            if(resourcesubService.count(new LambdaQueryWrapper<Resourcesub>().eq(Resourcesub::getResourceGroupId, dto.getResourceGroupIdIsF())) > 0) {
                return Result.error("更换生产线类别，需要清空下面的机器设备关联。");
            }
        }
        Resource resource = new Resource();
        BeanUtils.copyPropertiesIgnoreCase(dto, resource);
        resourceService.updateById(resource);
        Resourcegroup resourcegroup = new Resourcegroup();
        resourcegroup.setResourceGroupId(dto.getResourceGroupIdIsF());
        resourcegroup.setResourceGroupNO(dto.getDeviceId());
        resourcegroup.setResourceGroupName(dto.getDeviceName());
        resourcegroup.setResourceGroupParentId(dto.getResourceGroupId());
        resourceGroupService.updateById(resourcegroup);
        return Result.success("编辑成功");
    }

    @Log("添加生产线-设备")
    @ApiOperation("添加生产线-设备")
    @PostMapping("addProductLineDevice")
    @DSTransactional
    public Result addProductLineDevice(@RequestBody AddProductLineDeviceDto dto) {
        if(dto.getDeviceResourceGroupId() == null ||dto.getNums() == null ||
        dto.getResourceGroupId() == null) {
            return Result.error("资源组ID,设备组/设备ID,数量不能为空");
        }
//        Integer count = resourcegroupMapper.selectCount(new LambdaQueryWrapper<Resourcegroup>()
//                .eq(Resourcegroup::getResourceGroupId, resource.getResourceGroupId()));
//        if(count == null || count == 0) {
//            return Result.error("资源组ID不存在");
//        }
        Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, dto.getResourceGroupId()));
        if(resource == null || resource.getFixedLine() == null) {
            return Result.error("请先设置生产线为固定线/变动线!");
        }
        int f = resourcesubService.count(new LambdaQueryWrapper<Resourcesub>().eq(Resourcesub::getResourceGroupId, dto.getResourceGroupId())
                .eq(Resourcesub::getDeviceResourceGroupId, dto.getDeviceResourceGroupId()));
        if(f > 0) {
            return Result.error("已存在该设备资源!");
        }
        Resourcesub resourcesub = new Resourcesub();
        BeanUtils.copyPropertiesIgnoreCase(dto, resourcesub);
        boolean b = resourcesubService.save(resourcesub);
        if(b) return Result.success("添加生产线-设备成功");
        else return Result.success("添加生产线-设备失败");
    }

    @Log("删除生产线-设备")
    @ApiOperation("删除生产线-设备")
    @PostMapping("delProductLineDevice")
    @DSTransactional
    public Result delProductLineDevice(@RequestBody Integer resourceSubId) {
        if(resourceSubId == 0) {
            return Result.error("资源子表ID不能为空");
        }
        boolean b = resourcesubService.removeById(resourceSubId);
        if(b) return Result.success("删除生产线-设备成功");
        else return Result.success("删除生产线-设备失败");
    }

    @Log("编辑生产线-设备")
    @ApiOperation("编辑生产线-设备")
    @PostMapping("editProductLineDevice")
    @DSTransactional
    public Result editProductLineDevice(@RequestBody Resourcesub dto) {
        if(dto.getResourceSubId() == null || dto.getResourceGroupId() == null || dto.getDeviceResourceGroupId() == null || dto.getNums() == null) {
            return Result.error("资源子表ID, 数量, 生产线ID, 设备ID不能为空");
        }
        Resourcesub one = resourcesubService.getOne(new LambdaQueryWrapper<Resourcesub>().eq(Resourcesub::getResourceGroupId, dto.getResourceGroupId())
                .eq(Resourcesub::getDeviceResourceGroupId, dto.getDeviceResourceGroupId()));
        if(one != null && !one.getResourceSubId().equals(dto.getResourceSubId())) {
            return Result.error("已存在该设备资源!");
        }
        boolean b = resourcesubService.updateById(dto);
        if(b) return Result.success("编辑生产线-设备成功");
        else return Result.success("编辑生产线-设备失败");
    }

}
